package com.shareppy.norman.sqlite.em;

import android.content.Context;

import com.shareppy.norman.core.em.EntityManager;
import com.shareppy.norman.core.entity.AbstractEntity;
import com.shareppy.norman.core.procedures.InitialData;
import com.shareppy.norman.core.queries.ComplexQuery;
import com.shareppy.norman.sqlite.db.SQLiteConnection;
import com.shareppy.norman.sqlite.db.SQLiteDBHelper;

public class EMF {

	private static SQLiteDBHelper helper;

	public static void configure(Context context, String dbname, int dbversion,
			Class<? extends AbstractEntity>... entities) {
		EMF.configure(context, dbname, dbversion, null, entities);
	}

	public static void configure(Context context, String dbname, int dbversion,
			InitialData initialScript,
			Class<? extends AbstractEntity>... entities) {
		helper = new SQLiteDBHelper(context, dbname, dbversion, initialScript,
				entities);
	}

	public static EntityManager getEM() {
		return EMF.getEM(false);
	}

	public static EntityManager getEM(SQLiteConnection conn) {
		return new SQLiteEntityManager(conn);
	}

	public static EntityManager getEM(boolean writeable) {
		SQLiteEntityManager.oConnections++;
		// System.out.println("Conexiones abiertas(+): "+AndroidEntityManager.oConnections);
		return new SQLiteEntityManager(new SQLiteConnection(
				writeable ? helper.getWritableDatabase()
						: helper.getReadableDatabase()));
	}

	public static void release(EntityManager em) {
		em.release();
	}

	public static <T extends AbstractEntity> void saveAndIgnoreError(
			T... entities) {
		try {
			saveEntity(entities);
		} catch (Exception e) {
			//
		}
	}

	public static <T extends AbstractEntity> void saveEntity(T... entities)
			throws Exception {
		EntityManager em = EMF.getEM(true);
		try {
			for (T entity : entities) {
				em.save(entity);
			}
		} finally {
			em.release();
		}
	}

	public static <E extends AbstractEntity, R> R query(
			ComplexQuery<E, R> complexQuery) throws Exception {
		EntityManager em = EMF.getEM();
		try {
			return em.query(complexQuery);
		} finally {
			em.release();
		}
	}
}